package com.OrderFood;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

public class JSONDemoServlet extends HttpServlet {

	private static final long serialVersionUID = -7368225680407826408L;
	private List<User> list;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		prepareData();
		JSONArray array = new JSONArray();

		for (User bean : list) {
			JSONObject obj = new JSONObject();
			try {

				obj.put("id", bean.getId());
				obj.put("name", bean.getName());
//				obj.put("email", bean.getEmail());
				obj.put("gender", bean.getGender());
					
				//response.getWriter().print(obj.toString());
			} catch (Exception e) {

			}
			array.put(obj);
		}
		
		response.getWriter().print(array.toString());
		
		//out.write(array.toString());
		//System.out.println(response.encodeRedirectURL(array.toString()));	
		System.out.println(array.toString());
		out.flush();
		out.close();
	}

	private void prepareData() {
		list = new ArrayList<User>();
		User bean1 = new User();
		bean1.setId(1001);
		bean1.setName("Tom");
		bean1.setGender("male");
		list.add(bean1);

		User bean2 = new User();
		bean2.setId(1002);
		bean2.setName("Lily");
		bean2.setGender("female");
		list.add(bean2);

		User bean3 = new User();
		bean3.setId(1003);
		bean3.setName("Deen");
		bean3.setGender("male");
		list.add(bean3);

//		User bean4 = new User();
//		bean4.setId(1004);
//		list.add(bean4);
	}

}
